﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Baosight.ZNH.ZMCommon.ChildWindows;
using Baosight.Platform.Core.UI.Controls;
using Baosight.Platform.Core.ServiceModel;
using Baosight.Platform.Core;
using Baosight.ZNH.ZMCommon;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;

namespace Baosight.ZNH.ZMCP.UI.PopWindows
{
    public partial class ProfessionalHolePlanDetailBU : EFViewCmes
    {
        public ProfessionalHolePlanDetailBU(string dialogType)
        {
            InitializeComponent();
            base.BeforeAction += OnBeforeAction;
            Init(dialogType);
        }

        /// <summary>
        /// 初始化父类EFViewCmesProperty的值，每次点击“确定”、“返回”时执行此方法，从新赋值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnBeforeAction(object sender, EventArgs e)
        {
            EFViewCmesProperty _view = new EFViewCmesProperty();
            _view.DataFields = this.spWindows.GetChildObjects<EFDataField>(null, true);
            base.ViewProperty = _view;
        }

        /// <summary>
        /// 初始化页面数据
        /// </summary>
        private void Init(string type)
        {
            type = type == null ? "insert" : type.ToLower();

            switch (type)
            {
                case "insert":
                    base.Mode = OperationMode.Insert;
                    break;
                case "update":
                    base.Mode = OperationMode.Update;
                    break;
                case "batchUpdate":
                    //base.Mode = OperationMode.Update;
                    break;
                case "detail":
                    this.Commit.Visibility = Visibility.Collapsed;
                    BaseTools.EFDataFieldNotEnabled(this.spWindows.GetChildObjects<EFDataField>(null, true));
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 确定按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CommitClick(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            button.IsEnabled = false;
            TempButton = button;

            List<string> list = new List<string>();
            if (!this.grid.Validate(DataRange.CheckedItems, out list))
            {
                this.ValidateMessagePopup();//弹出提示信息
                this.TempButtonOpen(true);//确定按钮生效
                return;
            }

            foreach (var row in this.grid.EIBlock.GetRows())
            {
                if (!validateDate(row["fdStartDate"].ToString().Split('-')))
                {
                    this.TempButtonOpen(true);//确定按钮生效
                    return;
                }

                if (!validateDate(row["fdEndDate"].ToString().Split('-')))
                {
                    this.TempButtonOpen(true);//确定按钮生效
                    return;
                }

                if (row["fdStartDate"].ToString().CompareTo(row["fdEndDate"].ToString()) > 0)
                {
                    base.OpenEFWindowAlert("开始时间不能大于结束时间！", true);
                    this.TempButtonOpen(true);//确定按钮生效
                    return;
                }

                string outId = row["fdProjectId"].ToString();
                string outStart = row["fdStartDate"].ToString();
                string outEnd = row["fdEndDate"].ToString();

                foreach (var _row in this.grid.EIBlock.GetRows())
                {
                    string inId = _row["fdProjectId"].ToString();
                    string inStart = _row["fdStartDate"].ToString();
                    string inEnd = _row["fdEndDate"].ToString();

                    if (!row.RowId.Equals(_row.RowId) && outId.Equals(inId))
                    {
                        if (inStart.CompareTo(outEnd) > 0 || inEnd.CompareTo(outStart) < 0)
                        {
                            //正常的日期，即同一个工程的开始日期，截止日期段没有重复
                        }
                        else
                        {
                            base.OpenEFWindowAlert( row["fdName"] + "的开始日期至截止日期时间段有重复，请重新选择！", true);
                            return;
                        }
                    }
                }

            }

            EIInfo eiInfo = new EIInfo();
            eiInfo.Attributes.Add(EIConstants.ServiceNameKey, "ZMCP03");
            eiInfo.Attributes.Add(EIConstants.MethodNameKey, "batchUpdate");
            eiInfo.Attributes.Add("fdPlanmainId", this.fdPlanmainId.Value.ToString());

            EIBlock eiBlock = new EIBlock("result");
            eiBlock.SetColumns(this.grid.EIBlock.GetColumns());
            eiBlock.SetRows(this.grid.EIBlock.GetRows());

            eiInfo.AddBlock(eiBlock);

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, DoworkCompleted);
        }

        private void DoworkCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            EIInfo inInfo = e.EIInfo;
            if (inInfo.Status == -1)
            {
                this.TempButtonOpen(true);
                this.OnCommitMessagePopup(inInfo);//操作失败，消息提醒
            }
            else
            {
                //操作成功关闭新增页面
                //此处可以扩展是否连续新增
                EFWindow window = this.Parent as EFWindow;
                window.DialogResult = true;
                window.Close();
            }
        }
        /// <summary>
        /// 取消按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CancelClick(object sender, RoutedEventArgs e)
        {
            CmesWindows _window = this.Parent as CmesWindows;
            _window.DialogResult = false;
            _window.Close();
        }

        private void grid_CellEditEnded(object sender, Telerik.Windows.Controls.GridViewCellEditEndedEventArgs e)
        {
            IEFColumn column = e.Cell.Column as IEFColumn;
            if (column != null)
            {
                if (column.eColumnName.Equals("fdNo"))
                {
                    RadComboBox select = (e.Cell.Content as GridViewEditorPresenter).Content as RadComboBox;
                    UIBaseEntity obj = e.Cell.ParentRow.DataContext as UIBaseEntity;
                    EIRow row = obj.GetEIRow();
                    if (select.SelectedItem != null)
                    {
                        row["fdName"] = select.SelectedItem.GetType().GetProperty("fdName").GetValue(select.SelectedItem, null);
                        row["fdNo"] = select.SelectedItem.GetType().GetProperty("fdNo").GetValue(select.SelectedItem, null);
                        row["fdProjectPlace"] = select.SelectedItem.GetType().GetProperty("fdProjectPlace").GetValue(select.SelectedItem, null);
                        
                        row["fdStatus"] = select.SelectedItem.GetType().GetProperty("fdStatus").GetValue(select.SelectedItem, null);
                        row["fdProjectId"] = select.SelectedItem.GetType().GetProperty("fdKeyId").GetValue(select.SelectedItem, null);
                        row["fdProjectType"] = select.SelectedItem.GetType().GetProperty("fdClass").GetValue(select.SelectedItem, null);
                    }
                }
                else if (column.eColumnName.Equals("fdMeterperhole") || column.eColumnName.Equals("fdHoleNum"))
                {
                    UIBaseEntity obj = e.Cell.ParentRow.DataContext as UIBaseEntity;
                    EIRow row = obj.GetEIRow();
                    row["fdHoleLength"] = double.Parse(row["fdMeterperhole"].ToString()) * double.Parse(row["fdHoleNum"].ToString());
                }
            }
        }

        private bool validateDate(string[] date)
        {
            if (int.Parse(this.fdPlanYear.Value.ToString()) != int.Parse(date[0]))
            {
                base.OpenEFWindowAlert("所选择的日期年份不是计划年份，请重新选择年份！", true);
                return false;
            }

            if (int.Parse(this.fdPlanMonth.Value.ToString()) != int.Parse(date[1]))
            {
                base.OpenEFWindowAlert("所选择的日期月份不是计划月份，请重新选择月份！", true);
                return false;
            }
            return true;
        }
    }
}
